'''
python 调用lua 函数
# https://tool.4xseo.com/article/202945.html

'''
import lupa
import json
import time
# 实例化一个lua解释器
lua = lupa.LuaRuntime()
aa = {
    "a": 5,
    "c": None,
    "b": ["a", "b"]
}
a = {
    "a": 5,
    "c": None,
    "b": 9,
    "d": aa
}
# jsonchang = '''
#      function(d)
#          local t = {}
#          for key, value in python.iterex(d.items()) do
#              t[key] = value
#             print(key,value,type(value))

#          end
#          t['d']['c'] = 'dfd'
#          t['d']['b'] = {"Lua", "Tutorial"}
#          return t
#      end
#     '''
# lua_func = lua.eval(jsonchang)


valuechange = '''
     function(d)
         local t = {ca='c',cd={'ab','bc','cd'}}
         for key, value in python.iterex(d.items()) do
             t[key] = value
            print(key,value,type(value))

         end
         t['d']['c'] = 'dfd'
         t['d']['b'] = {"Lua", "Tutorial"}
         return t
     end
    '''
lua_func = lua.eval(valuechange)
# starttime = time.time()

r = lua_func(lupa.as_attrgetter(a)
             )
# print(time.time()-starttime)
print(r['c'])
print(r, type(r))  # 6

result = {}


def table_conver_dict(tablev, dictv):
    '''
    {"error_code":0,
    "error_message":None,
    "result":{}
    }
    将lua的 table 表结构转为python dict字典
    table中不含 nil 同意使用'None' 
    遇到列表特殊处理
    '''
    templist = []
    valueone = None
    for key, value in tablev.items():
        # print(f'{key},{value},{str(type(value))}')
        if type(key) in [str]:
            if type(value) in [str] and value == 'None':
                dictv[key] = None
            if type(value) in [str, int]:
                dictv[key] = value

            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                dictv[key] = {}
                a = table_conver_dict(value, dictv[key])
                if a:
                    dictv[key] = a

        elif type(key) in [int] and key == 1:
            templist = []
            if type(value) in [str] and value == 'None':
                valueone = None
            elif type(value) in [str, int]:
                valueone = value

            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                valueone = {}
                a = table_conver_dict(value, valueone)
                if a:
                    valueone = a
            templist.append(valueone)
        elif type(key) in [int]:

            if type(value) in [str] and value == 'None':
                valueone = None
            elif type(value) in [str, int]:
                valueone = value

            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                valueone = {}
                a = table_conver_dict(value, valueone)
                if a:
                    valueone = a
            templist.append(valueone)
    if templist:
        return templist
    else:
        return False


starttime = time.time()
a = table_conver_dict(r, result)
if a:
    result = a
print(time.time()-starttime)
print(result, type(result))
print(result['d']['b'][0])
print(result['d']['b'][1])
for key, value in result['d'].items():
    print(f'{key},{value},{type(key)},{str(type(value))}')
for value in result['d']['b']:
    print(f'{value},{type(value)}')
# a = {
#     "a": 5,
#     "b": 9
# }
# select = '''
#     function (obj)
#         print("mytable type is  ",type(obj))
#         return obj["b"]
#     end
#     '''
# lua_func = lua.eval(select)

# r = lua_func(a)


# print(r, type(r))  # 6
